import { Component, Inject, Output, EventEmitter, OnInit } from '@angular/core';
import { MdDialog, MdDialogRef, MD_DIALOG_DATA } from '@angular/material';

import { Doctor }             from '../../../domain/doctor.mdl';
import { DlgMode }              from '../../../domain/definitions';

import { DoctorService }  from '../../../services/doctor.service';
import { AuthService }      from '../../../services/auth.service';

@Component({
  selector: 'doctor-dialog-form',
  templateUrl: 'doctor.dialog.form.html',
  styles: [
    `.dlgheader {
      height:30px;
    }
    .dlgbody{
      width: 660px;
      height:400px;
    }
    .dlgfooter{
      height:30px;
    }
    .full-width {
      width: 100%;
    }`
  ]
})
export class DoctorDialogForm implements OnInit {
  doctor:Doctor;
  dlgTitle:string = 'AddDoctor';
  
  private dlgMode:DlgMode = DlgMode.Add;
  
  constructor(@Inject(MD_DIALOG_DATA) public data: any,
    public dialogRef: MdDialogRef<DoctorDialogForm>,
    private doctorService: DoctorService,
    private authService:AuthService) {
    this.doctor = new Doctor({name:'',worktel:'',homeaddress:''});
    console.log('DoctorDialogForm:constructor() called.');
  }
	  
  
  ngOnInit(): void {
    if(this.data){
      console.log(JSON.stringify(this.data,null,2));
      this.dlgMode = DlgMode.Edit;
      this.doctor = this.data;
      
      this.dlgTitle = 'EditDoctor';
    }
    console.log('DoctorDialogForm:constructor() called.');
  }
  
  closeDlg():void {
    this.dialogRef.close(this.doctor);
  }

  onSubmit():void {
    //console.log('1.doctor=',this.doctor);    
    //this.doctor.alertPolicy = JSON.parse(this.alertPolicyStr);
    console.log('2.hospital=',this.doctor);
    if(this.dlgMode == DlgMode.Add) {
      console.log('do add task.');
     // var userInfo = this.authService.getUserInfo();
     // console.log('userInfo=',userInfo);
      this.doctorService.addDoctor(this.doctor).subscribe(
        doctor => {
          this.doctor = doctor;
          //this.onLocationAdded.emit(this.doctor);
          layer.msg('add success.');
          this.closeDlg();
        },
        error => {
          layer.msg('add failed.'+error);
        }
      );
    }
    if(this.dlgMode == DlgMode.Edit){
      console.log('do edit task.');
      this.doctorService.updateDoctor(this.doctor).subscribe(
        doctor =>{
          this.doctor = doctor;
          layer.msg('update success.');
          this.closeDlg();
        },
        error =>{
          layer.msg('update failed.'+error);
        }
      );
    }
    this.dialogRef.close(this.doctor);
  }
}
